package pers.hl.library.utils;

import com.google.gson.JsonObject;
import org.springframework.util.StringUtils;
import pers.hl.library.common.Const;
import pers.hl.library.enums.FileType;
import pers.hl.library.po.FileEntity;
import pers.hl.library.service.FileService;

import java.io.File;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 保存二维码文件工具类，用于文件写入服务器及入库
 */
public class QRFileSaveHelper {

    private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

    public static void saveFile(int fileType, int bussId, FileService fileService) {
        executorService.execute(() -> {
            String fileUrl = null;
            if (fileType == FileType.BOOK_QRCODE.value() || fileType == FileType.USER_QR_CODE.value()) {
                fileUrl = saveQrCode(fileType, bussId);
            }
            if (StringUtils.isEmpty(fileUrl)) {
                ExceptionHelper.throw500("save file failed");
                LogUtils.e(String.format("save file failed, type=%s, bussId=%s", fileType, bussId));
            }
            save2Database(fileType, bussId, fileUrl, fileService);
        });
    }

    private static void save2Database(int fileType, int bussId, String fileUrl, FileService fileService) {
        // 创建文件表对应实体，并写入数据库
        FileEntity fileEntity = new FileEntity();
        fileEntity.setFileType(fileType);
        fileEntity.setFileBussId(bussId);
        fileEntity.setFileUrl(fileUrl);
        Date curDate = new Date();
        fileEntity.setFileCreateTime(curDate);
        fileEntity.setFileUpdateTime(curDate);
        if (!fileService.addData(fileEntity)) {
            LogUtils.e(String.format("write file to database fail, type=%s, bussId=%s", fileType, bussId));
        } else {
            LogUtils.i(String.format("write file to database successfully, type=%s, bussId=%s, fileUrl=%s", fileType, bussId, fileUrl));
        }
    }

    private static String saveQrCode(int fileType, int bussId) {
        //这里采用主键id+文件type的形式作为二维码内容，满足多场景下扫码的需求
        JsonObject object = new JsonObject();
        object.addProperty("id", bussId);
        object.addProperty("type", fileType);
        String content = GsonUtils.toJson(object);
        LogUtils.i("generateQrCode, json:" + content);
        File dest = null;
        try {
            if (fileType == FileType.BOOK_QRCODE.value()) {
                dest = QRCodeUtil.QREncode(content, Const.FilePath.QRCODE_PATH, Const.FilePath.DEFAULT_BOOK_QR_IMG_PATH);
            } else if (fileType == FileType.USER_QR_CODE.value()) {
                dest = QRCodeUtil.QREncode(content, Const.FilePath.FILE_AVATAR_PATH, Const.FilePath.DEFAULT_AVATAR_PATH);
            }
        } catch (Exception e) {
            LogUtils.e("generateQrCode failed");
            e.printStackTrace();
        }
        return dest != null ? dest.getAbsolutePath() : null;
    }
}
